<?php

namespace App\Services\Goods;

use App\Inputs\GoodsListInput;
use App\Models\Goods\Footprint;
use App\Models\Goods\Goods;
use App\Models\Goods\GoodsAttribute;
use App\Models\Goods\GoodsProduct;
use App\Models\Goods\GoodsSpecification;
use App\Models\Goods\Issue;
use App\Models\Order\Cart;
use App\Services\BaseServices;
use Illuminate\Database\Eloquent\Builder;

class GoodsServices extends BaseServices
{
    /**
     * 批量获取商品
     * @param  array  $ids
     *
     * @return Builder[]|\Illuminate\Database\Eloquent\Collection|\Illuminate\Support\Collection
     */
    public function getGoodsListByIds(array $ids)
    {
        if (empty($ids)) {
            return collect();
        }
        return Goods::query()->whereIn('id', $ids)->get();
    }

    /**
     * 返回商品详情
     *
     * @param  int  $id
     *
     * @return Builder|Builder[]|\Illuminate\Database\Eloquent\Collection|\Illuminate\Database\Eloquent\Model|null
     */
    public function getGoods(int $id)
    {
        return Goods::query()->find($id);
    }

    /**
     * 返回商品属性
     *
     * @param  int  $goodsId
     *
     * @return Builder[]|\Illuminate\Database\Eloquent\Collection
     */
    public function getGoodsAttribute(int $goodsId)
    {
        return GoodsAttribute::query()->where('goods_id', $goodsId)->where('deleted', 0)->get();
    }

    /**
     * 获取商品sku属性
     *
     * @param  int  $goodsId
     *
     * @return Builder[]|\Illuminate\Database\Eloquent\Collection|\Illuminate\Support\Collection
     */
    public function getGoodsSpecification(int $goodsId)
    {
        $spec = GoodsSpecification::query()->where('goods_id', $goodsId)->where('deleted', 0)
            ->get()->groupBy('specification');
        return $spec->map(function ($v, $k) {
            return ['name' => $k, 'valueList' => $v];
        })->values();
    }

    public function getGoodsProductById(int $id)
    {
        return GoodsProduct::query()->find($id);
    }

    public function getGoodsProductsByIds(array $ids)
    {
        if (empty($ids)) {
            return collect();
        }
        return GoodsProduct::query()->whereIn('id', $ids)->get();
    }


    /**
     * 返回sku商品详情
     *
     * @param  int  $goodsId
     *
     * @return Builder[]|\Illuminate\Database\Eloquent\Collection
     */
    public function getGoodsProduct(int $goodsId)
    {
        return GoodsProduct::query()->where('goods_id', $goodsId)->where('deleted', 0)->get();
    }

    /**
     * 查询商品问题
     *
     * @param  int  $page
     * @param  int  $limit
     *
     * @return Builder[]|\Illuminate\Database\Eloquent\Collection
     */
    public function getGoodsIssue(int $page = 1, int $limit = 4)
    {
        return Issue::query()->forPage($page, $limit)->get();
    }

    /**
     * 保存用户足迹
     *
     * @param $userId 用户ID
     * @param $goodsId 商品ID
     *
     * @return bool
     */
    public function saveFootPrint($userId, $goodsId)
    {
        $footprint = new Footprint();
        $footprint->fill(['user_id' => $userId, 'goods_id' => $goodsId]);
        return $footprint->save();
    }

    /**
     * 获取在售商品的数量
     *
     * @return int
     */
    public function countGoodsOnSale()
    {
        return Goods::query()->where('is_on_sale', 1)->where('deleted', 0)->count('id');
    }

    //public function listGoods($categoryId,$brandId,$isNew,$isHot,$keyword,$sort='add_time',$order='desc',$page=1,$limit=10,$columns=['*'])
    public function listGoods(GoodsListInput $input, $columns)
    {
        //$query = $this->getQueryByGoodsFilter($brandId,$isNew,$isHot,$keyword);
        $query = $this->getQueryByGoodsFilter($input);
        //if(!empty($categoryId)) {
        if (!empty($input->categoryId)) {
            $query = $query->where('category_id', $input->categoryId);
        }
        return $query->orderBy($input->sort, $input->order)->paginate($input->limit, $columns, 'page', $input->page);
    }

    //public function listL2Category($brandId,$isNew,$isHot,$keyword){
    public function listL2Category(GoodsListInput $input)
    {
        //$query = $this->getQueryByGoodsFilter($brandId,$isNew,$isHot,$keyword);
        $query = $this->getQueryByGoodsFilter($input);
        $categoryIds = $query->select(['category_id'])->pluck('category_id')->unique()->toArray();
        return CatalogServices::getInstance()->getL2ListByIds($categoryIds);
    }

    //private function getQueryByGoodsFilter($brandId,$isNew,$isHot,$keyword)
    private function getQueryByGoodsFilter(GoodsListInput $input)
    {
        $query = Goods::query()->where('is_on_sale', 1)
            ->where('deleted', 0);
        //if(!empty($brandId)) {
        if (!empty($input->brandId)) {
            $query = $query->where('brand_id', $input->brandId);
        }
        if (!is_null($input->isNew)) {
            $query = $query->where('is_new', $input->isNew);
        }
        if (!is_null($input->isHot)) {
            $query = $query->where('is_hot', $input->isHot);
        }
        if (!empty($input->keyword)) {
            $query = $query->where(function (Builder $query) use ($input) {
                $query->where('keywords', 'like', "%{$input->keyword}%")
                    ->orWhere('name', 'like', "%{$input->keyword}%");
            });
        }
        return $query;
    }

    public function reduceStock($productId, $num)
    {
        return GoodsProduct::query()->where('id', $productId)->where('number', '>=', $num)
            ->decrement('number', $num);
    }

    public function addStock($productId, $num)
    {
        $product = $this->getGoodsProductById($productId);
        $product->number = $product->number + $num;
        return $product->cas();
    }

}
